/** 
 * @Description: 文件描述
 * @Author: 程前
 * @Date: 2024-12-24 16:29:54
 * @LastEditors: 程前
 * @LastEditTime: 2024-12-25 17:00:58
 */


import {
    Cartesian2,
    WebMercatorTilingScheme,
    UrlTemplateImageryProvider,
} from "cesium";

import BD09TilingScheme from "../tiling/BD09TilingScheme";

const LAYER_TILE_URL: any = {
    img: "//shangetu{s}.map.bdimg.com/it/u=x={x};y={y};z={z};v=009;type=sate&fm=46",
    vec: "//online{s}.map.bdimg.com/tile/?qt=tile&x={x}&y={y}&z={z}&styles=sl&v=020",
    custom:
        "//api{s}.map.bdimg.com/customimage/tile?&x={x}&y={y}&z={z}&scale=1&customid={style}",
    traffic:
        "//its.map.baidu.com:8002/traffic/TrafficTileService?time={time}&label={labelStyle}&v=016&level={z}&x={x}&y={y}&scaler=2",
};

/**
 * @description 处理UrlTemplateImageryProvider所需要的参数
 * @param {String} options 原始的options参数
 * @return {UrlTemplateImageryProvider.ConstructorOptions}
 */
const getOptions = (
    options: any
): UrlTemplateImageryProvider.ConstructorOptions => {
    options.crs = options.crs || "BD09"; // WGS84 | BD09
    const urlTemplate =
        options.url || LAYER_TILE_URL[options?.tileType] || LAYER_TILE_URL.img;
    const url: string = urlTemplate; // replacePlaceholders(urlTemplate, options)
    let LayerOption: UrlTemplateImageryProvider.ConstructorOptions = {
        url: url,
        maximumLevel: options.maximumLevel || 18,
        minimumLevel: options.minimumLevel || 1,
    };

    if (options.crs === "WGS84") {
        let resolutions = [];
        for (let i = 0; i < 19; i++) {
            resolutions[i] = 256 * Math.pow(2, 18 - i);
        }
        LayerOption["tilingScheme"] = new BD09TilingScheme({
            resolutions,
            rectangleSouthwestInMeters: new Cartesian2(-20037726.37, -12474104.17),
            rectangleNortheastInMeters: new Cartesian2(20037726.37, 12474104.17),
        });
    } else {
        LayerOption["tilingScheme"] = new WebMercatorTilingScheme({
            rectangleSouthwestInMeters: new Cartesian2(-33554054, -33746824),
            rectangleNortheastInMeters: new Cartesian2(33554054, 33746824),
        });
    }
    return LayerOption;
};

/**
 * 创建百度图层provider
 * @param opts 
 * @returns 
 */
export const createBaiduImageryProvider = (opts: any): UrlTemplateImageryProvider => {
    const provideOptions: UrlTemplateImageryProvider.ConstructorOptions =
        getOptions(opts);
    return new UrlTemplateImageryProvider(provideOptions);
};
